/*
 * Copyright 2020-2025 the original author or authors.
 * You cannot use this file unless authorized by the author.
 */
package org.ipig.commons.service.retry;

import org.ipig.commons.exception.UnsupportException;

/**
 * 可重试服务
 * <pre>调用案例：{@code
 * RetryAbleService retryService = new RetryAbleService() {
 *     @Override
 *     public boolean process() {
 *         boolean retryAble = false;
 *         //处理业务......
 *         return retryAble;
 *     }
 *     @Override
 *     public void retryFailed() {
 *         //多次重试之后，最终失败的回调处理......
 *     }
 * };
 * }</pre>
 * boolean retryResult = retryService.retry(3, 500);
 *
 * @author <a href="mailto:comchnts@163.com">chinats</a>
 * @version $$Id: RetryAbleService.java 10 2020-04-10 02:44:38Z ts <comchnts@163.com> $$
 * @since 1.0
 */
public interface RetryAbleService {

    /**
     * 重试,默认3次，每0.3秒一次
     */
    public default boolean retry() {
        return retry(3, 300);
    }

    /**
     * 重试
     *
     * @param retryMaxQty 重试次数
     * @param waitMillis  等待时间
     */
    public default boolean retry(final int retryMaxQty, final long waitMillis) {
        boolean returnFlag = true;
        boolean retryFlag = true;
        int doneTimes = 0;
        while (retryFlag) {
            try {
                retryFlag = !process();
            } catch (UnsupportException ex) {
                throw new UnsupportException(ex.getMessage());
            } catch (Throwable ex) {
                ex.printStackTrace();
                retryFlag = true;
            } finally {
                doneTimes++;
            }
            if (retryFlag && retryMaxQty > 0 && doneTimes > retryMaxQty) {
                retryFlag = false;//超过最大重试次数,不进行重试
                returnFlag = false;
                try {
                    retryFailed();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                break;
            }
            if (retryFlag) {
                try {
                    Thread.sleep(waitMillis);
                } catch (InterruptedException ex) {
                }
            }
        }
        return returnFlag;
    }

    /**
     * 重试失败的最终处理方式
     */
    public abstract void retryFailed();

    /**
     * 处理业务
     *
     * @return true: 处理成功；false 处理失败,等待重试
     */
    public abstract boolean process();
}
